<?php

namespace App\Http\Controllers\Api;

use App\Models\Order;
use App\Models\UserAddress;
use App\Services\OrderService;
use App\Services\PayService;
use Illuminate\Http\Request;

class OrdersController extends ApiController
{
    protected $payService;
    public function __construct(PayService $payService)
    {
        $this->payService = $payService;
    }
    // 获取订单
    public function index(Request $request)
    {
        if ($request->search) {
            $orders = $this->searchOrderList($request->search);
        } else {
            $orders = $this->getOrderList($request->type, $request->skip, $request->limit);
        }
        $data['orders'] = $orders;
        return $this->success($data);
    }
    // 获取订单列表
    public function getOrderList($type = '', $skip = 0, $limit = 8)
    {
        $query = Order::query()->with(['items.product','items.productSku'])->where('user_id', auth('api')->user()->id);
        $query = $this->statusByWhere($type, $query);
        $results = $query->skip($skip)->take($limit)->orderBy('created_at', 'desc')->get();
        $orders = [];
        foreach ($results as $order) {
            $orders[] = Order::tidyOrder($order);
        }
        return $orders;
    }
    // 查询订单
    public function searchOrderList($search = '')
    {
        $results = Order::query()->with(['items.product','items.productSku'])->where('user_id', auth('api')->user()->id)->where('no', 'like', '%' . $search . '%')->orderBy('created_at', 'desc')->get();
        $orders = [];
        foreach ($results as $order) {
            $orders[] = Order::tidyOrder($order);
        }
        return $orders;
    }
    // 状态查询条件
    public static function statusByWhere($status, $model = null)
    {
        switch ($status) {
            case '0': //代付款
                return $model->whereNull('paid_at')->where('refund_status', 'pending');
                break;
            case '1': //待发货
                return $model->whereNotNull('paid_at')->where('refund_status', 'pending')->where('ship_status', 'pending');
                break;
            case '2': //待收货
                return $model->whereNotNull('paid_at')->where('refund_status', 'pending')->where('ship_status', 'delivered');
                break;
            case '3': //已完成
                return $model->whereNotNull('paid_at')->where('refund_status', 'pending')->where('ship_status', 'received');
                break;
            case '-2': //售后单
                return $model->whereNotNull('paid_at')->where('refund_status', '<>', 'pending');
                break;
            case '': //所有订单
            default:
                return $model;
                break;
        }
    }

    //通过ID获取订单
    public function getOrder(Request $request)
    {
        $order = Order::query()
        // 使用 with 方法预加载，避免N + 1问题
            ->with(['items.productSku'])
            ->with(['items.product'])
            ->where('user_id', auth('api')->user()->id)
            ->where('id', $request->id)
            ->first();
        $order = Order::tidyOrder($order);
        $data['order'] = $order;
        return $this->success($data);
    }
    //创建订单
    public function store(Request $request, OrderService $orderService)
    {
        $user = auth('api')->user();
        $address = UserAddress::find($request->input('address_id'));
        $res = $orderService->store($user, $address, $request->input('remark'), $request->input('items'), $request->fromcart);
        if ($res['code'] && $res['code'] == 'error') {
            $data = $res['msg'];
            return $this->success($data, 'error');
        } else {
            $body = config('app.name');
            $fee = $res->total_amount;
            $tradeno = $res->no; // 订单编号
            $openid = auth('api')->user()->openid;
            $conf = $this->payService->getConfig($body, $tradeno, $fee, $openid);
            if ($conf['code'] == 'success') {
                $data['conf'] = $conf['data'];
                $data['order_id'] = $res->id;
                return $this->success($data);
            } else {
                return $this->success($conf['msg'], 'error');
            }
        }
        return $this->success('');
    }
    //重新支付订单
    public function rePay(Request $request)
    {
        $user = auth('api')->user();
        $order = Order::find($request->id);
        // 校验订单是否属于当前用户
        if ($order->user_id != auth('api')->user()->id) {
            return $this->success('订单状态异常', 'error');
        }
        // 判断订单的发货状态是否为已发货
        if ($order->paid_at) {
            return $this->success('订单已经付款', 'error');
        }
        if ($order->ship_status !== Order::SHIP_STATUS_PENDING) {
            return $this->success('发货状态不正确', 'error');
        }

        $order->no =Order::findAvailableNo();
        $order->save();
        $body = '娜美达商城';
        $fee = $order->total_amount;
        $tradeno = $order->no; // 订单编号
        $openid = auth('api')->user()->openid;
        $conf = $this->payService->getConfig($body, $tradeno, $fee, $openid);
        if ($conf['code'] == 'success') {
            $data['conf'] = $conf['data'];
            $data['order_id'] = $order->id;
            return $this->success($data);
        } else {
            return $this->success($conf['msg'], 'error');
        }
    }
    //删除订单
    public function destroy($id)
    {
        $order = Order::find($id);
        if (auth('api')->user()->id == $order->user->id) {
            $order->delete();
            if ($order->trashed()) {
                return $this->success('');
            } else {
                return $this->success('删除失败', 'error');
            }
        } else {
            return $this->success('订单归属错误', 'error');
        }
    }
    //申请退款
    public function applyRefund(Order $order, Request $request)
    {
        // 校验订单是否属于当前用户
        if ($order->user_id != auth('api')->user()->id) {
            return $this->success('订单状态异常', 'error');
        }
        // 判断订单是否已付款
        if (!$order->paid_at) {
            return $this->success('未支付不可退款', 'error');
        }
        // 判断订单退款状态是否正确
        if ($order->refund_status !== Order::REFUND_STATUS_PENDING) {
            return $this->success('请勿重复申请', 'error');
        }
        // 将用户输入的退款理由放到订单的 extra 字段中
        $extra = $order->extra ?: [];
        $extra['refund_reason'] = $request->input('reason');
        // 将订单退款状态改为已申请退款
        $order->update([
            'refund_status' => Order::REFUND_STATUS_APPLIED,
            'extra' => $extra,
        ]);
        $order = Order::tidyOrder($order);
        $data['order'] = $order;
        return $this->success($data);
    }
    // 确认收货
    public function received(Order $order)
    {
        // 校验订单是否属于当前用户
        if ($order->user_id != auth('api')->user()->id) {
            return $this->success('订单状态异常', 'error');
        }
        // 判断订单的发货状态是否为已发货
        if ($order->ship_status !== Order::SHIP_STATUS_DELIVERED) {
            return $this->success('发货状态不正确', 'error');
        }

        // 更新发货状态为已收到
        $order->update(['ship_status' => Order::SHIP_STATUS_RECEIVED]);

        // 返回
        $data['order'] = $order;
        return $this->success($data);
    }
}
